<template>
  <div>
    <el-form ref="deptForm" label-width="120px" :model="form" :rules="formRules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for=" item in list" :key="item.id" :value="item.username" :label="item.username" />

        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeesSimple, addDepartments, getDepartmentsDetail, editDepartments } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const existCodeValid = (rules, value, callback) => {
      // 验证输出的编码在所有部门是否存在
      // 提取所有部门的code编码
      let existCodeList = this.originList.map(item => item.code)
      console.log(existCodeList, '所有的code')
      // 如果是编辑功能，我们就需要把自身的code编码从判断的code编码变量中移除
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      // 如果输入框里面的值是已经存在的code编码，includes:查询调用的他的数组里面有没有后面写的值，如果有就返回true，没有就返回false
      if (existCodeList.includes(value)) {
        // 存在就校验失败
        callback(new Error(`部门编码:${value}已经存在`))
      } else {
        // 不存在校验成功
        callback()
      }
    }
    const existNameValid = (rules, value, callback) => {
      // 如果是已经命名过的子项
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      console.log(existNameList, '已经使用过的部门名称')
      if (this.isEdit) {
        // 通过id在所有部门信息里面找到自己的当前项，然后找到自己的pid
        const pid = this.originList.filter(item => item.id === this.id).pid
        // 通过pid寻找和自己相同pid的兄弟元素
        const brothers = this.originList.filter(item => item.pid === pid)
        // 遍历排除自己之后所有的兄弟元素，提取里面的name，赋值给判断的name变量
        existNameList = brothers.filter(item => item.id !== this.id).map(item => item.name)
      }
      // 如果输入框里面的值是已经使用过的部门名称
      if (existNameList.includes(value)) {
        // 我就返回一个错误
        callback(new Error(`部门名称:${value}已经存在`))
      } else {
        // 如果不在已经使用过的名称里面，我就通过校验
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      formRules: {
        name: [
          { required: true, message: '请输入部门的名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入长度是1-50的部门名称', trigger: 'blur' },
          { validator: existNameValid, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门的编码', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入长度是1-50的部门编码', trigger: 'blur' },
          { validator: existCodeValid, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门的负责人', trigger: ['blur', 'change'] }

        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入长度是1-300的部门介绍码', trigger: 'blur' }
        ]
      },
      list: []
    }
  },
  /* watch: {
    id: {
      // 开启深度监听
      deep: true,
      // 立刻执行
      immediate: true,
      handler: function(newVal, oldVal) {
        console.log(newVal, oldVal)
        if (this.isEdit) {
          this.loadDepartmentsDetail()
        }
      }
    }
  }, */
  async created() {
    this.loadEmployeesSimple()
    if (this.isEdit) {
      this.loadDepartmentsDetail()
    }
  },
  methods: {
    // 关闭表单
    resetForm() {
      this.$refs.deptForm.resetFields() // 清空表单
    },
    async doAdd() {
      try {
        const { data } = await addDepartments({ ...this.form, pid: this.id })
        console.log(data)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    async doEdit() {
      // 编辑功能
      try {
        const res = await editDepartments(this.form)
        console.log(res, '编辑功能')
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    hSubmit() {
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hCancel() {
      this.$emit('close')
    },
    async loadEmployeesSimple() {
      try {
        const { data } = await getEmployeesSimple()

        this.list = data
      } catch (error) {
        console.log(error)
      }
    },
    async loadDepartmentsDetail() {
      const { data } = await getDepartmentsDetail(this.id)
      console.log(data, '获取部门详情')
      this.form = data
    }
  }
}
</script>

<style>

</style>
